﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace DongleTest.DB
{
    public class Upload 
    {
        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(int Description, int ReservedValue);

        private static string serverAdd = "http://test.icomwell.com";
        private static string port = "17000";
        private static string url_s = serverAdd + ":" + port + "/device/reg.json?type=wx&";

        private static string GetUrltoHtml(string Url, string type)
        {
            try
            {
                System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);
                // Get the response instance.
                System.Net.WebResponse wResp = wReq.GetResponse();
                System.IO.Stream respStream = wResp.GetResponseStream();

                using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type)))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (System.Exception ex)
            {
                string errorMsg = ex.Message;
            }
            return "";
        }

        public static bool UploadTestResult(string mac, string id)
        {
            string url = "http://test.icomwell.com:13000/productionDevice/integrationTestUpdate.htm?dataArr=["
                + @"{""macId"":""" + mac + @""",""devNum"":""" + id + @""",""integrationTestTime"":""" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + @"""}"
                + "]";

            string str = GetUrltoHtml(url, "utf-8");
            Regex reg = new Regex("(?<=\"code\": *)+[0-9]+(?=,)");
            str = reg.Match(str).Value;
            if (!"200".Equals(reg.Match(str).Value))
            {
                return false;
            }

            return true;
        }

        public static bool UploadMac(string mac)
        {
            string url = "http://test.icomwell.com:13000/productionDevice/pcbaTestBatchUpdate.htm?dataArr=["
                + @"{""macId"":""" + mac + @""",""pcbaTestTime"":""" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + @"""}"
                + "]";

            string str = GetUrltoHtml(url, "utf-8");
            Regex reg = new Regex("(?<=\"code\": *)+[0-9]+(?=,)");
            if (!"200".Equals(reg.Match(str).Value))
            {
                return false;
            }
            return true;
        }

        public static string GetQrCode(string sn, string mac)
        {
            string req = "sn=" + sn + "&macId=" + mac;
            string strRec = GetUrltoHtml(url_s + req, "utf-8");
            if(string.IsNullOrEmpty(strRec))
            {
                return "ERROR";
            }
            ReciveInfo jsonRec = Json.JsonToObject<ReciveInfo>(strRec);
            
            if (jsonRec.code == 200)
            {
                return jsonRec.data.qrticket;
            }
            else
            {
                return "ERROR";
            }

        }

        public static bool UploadMacAndSn(string sn, string mac)
        {
            string req = "sn=" + sn + "&macId=" + mac;
            string strRec = GetUrltoHtml(url_s + req, "utf-8");
            if (string.IsNullOrEmpty(strRec))
            {
                return false;
            }
            ReciveInfo jsonRec = Json.JsonToObject<ReciveInfo>(strRec);

            if (jsonRec.code == 200)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 获取MD5值
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private static string GetMd5(string data)
        {
            byte[] result = Encoding.Default.GetBytes(data);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(result);
            return BitConverter.ToString(output).Replace("-", "");
        }

        /// <summary>
        /// 网络是否连接
        /// </summary>
        public static bool IsConnectInternet
        {
            get { return InternetGetConnectedState(0, 0); }
        }

    }
}
